import {ModalForm, ProForm, ProFormInstance, ProFormText} from '@ant-design/pro-components';
import {message} from 'antd';
import {useEffect, useRef} from 'react';
import {waitTime} from '@/utils/request';
import {addArticle, updateArticle} from '@/services/api/article';
import {ProFormDatePicker, ProFormTextArea} from "@ant-design/pro-form/lib";
import moment from "moment";

interface InputDialogProps {
  detailData?: API.ArticleDTO;
  visible: boolean;
  onClose: (result: boolean) => void;
}

export default function InputDialog(props: InputDialogProps) {
  const form = useRef<ProFormInstance>(null);

  useEffect(() => {
    waitTime().then(() => {
      if (props.detailData) {
        form?.current?.setFieldsValue(props.detailData);
      } else {
        form?.current?.resetFields();
      }
    });
  }, [props.detailData, props.visible]);

  const onFinish = async (values: any) => {
    const {title, author, content, createdDate} = values;
    const data: API.ArticleDTO = {
      id: props.detailData?.id,
      title,
      author,
      content,
      createdDate
    };
    try {
      if (props.detailData) {
        await updateArticle(data, {throwError: true});
      } else {
        await addArticle(data, {throwError: true});
      }
    } catch (ex) {
      return true;
    }
    message.success('保存成功');
    props.onClose(true);
    return true;
  };

  return (
    <ModalForm
      width={600}
      onFinish={onFinish}
      formRef={form}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => props.onClose(false),
      }}
      title={props.detailData ? '修改文章' : '新建文章'}
      open={props.visible}
    >
      <ProForm.Group>
        <ProFormText
          name="title"
          label="文章标题"
          width={300}
          rules={[
            {
              required: true,
              message: '请输入文章标题！',
            },
          ]}
        />
        <ProFormText
          name="author"
          label="文章作者"
          width={200}
          rules={[
            {
              required: true,
              message: '请输入作者名字！',
            },
          ]}
        />
      </ProForm.Group>
      <ProFormTextArea
        name="content"
        label="文章内容"
        rules={[
          {
            required: true,
            message: '请输入文章内容！',
          },
        ]}
      />

      <ProFormDatePicker
        name="createdDate"
        label="文章发表日期"
        initialValue={moment()}
        rules={[
          {
            required: true,
            message: '请输入发表日期！',
          },
        ]}
      />
    </ModalForm>
  );
}
